Skip to content

Conversation

quaternic
Copy link
Contributor

@quaternic quaternic commented Aug 12, 2025

New utility in libm::support:

  • trait NarrowingDiv for dividing u2N / uN when the quotient fits in uN
  • a reasonable implementation of that for primitives up to u256 / u128

This is the inverse operation of unsigned widening multiplication:

let xy: u256 = u128::widen_mul(x, y);
assert_eq!(xy.checked_narrowing_div_rem(y), Some((x, 0))); // unless y == 0

The trait API is based on x86's div-instruction: quotient overflow happens exactly when the high half of the dividend is greater or equal to the divisor, which includes division by zero.

Split from #1002

Copy link
Contributor

@tgross35 tgross35 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks great, thanks for including detailed comments. A few requests, mostly surface level

///
/// # Safety
/// Requires that `n.leading_zeros() == 0` and `a < n`.
unsafe fn div_three_digits_by_two<U>(a0: U, a: U::D, n: U::D) -> (U, U::D)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe div_three_3x_by_2x or so? Just thinking that the inputs aren't really digits

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They are digits in base R = 2.pow(U::BITS), and this function does division of a 3-digit number by a 2-digit number in that base. Admittedly the signature is rather weird, passing the "high two thirds" of the 3-digit number as one U::D and the least significant third as a U.

Copy link
Contributor

@tgross35 tgross35 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks awesome!

@tgross35 tgross35 enabled auto-merge (squash) September 5, 2025 08:20
@tgross35 tgross35 disabled auto-merge September 5, 2025 08:20
@tgross35 tgross35 enabled auto-merge (squash) September 5, 2025 08:21
@tgross35 tgross35 merged commit a63d089 into rust-lang:master Sep 5, 2025
146 of 150 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants